// 基于 SnowLang Project (https://gitee.com/jcnc-org/snow) 的衍生作品
// 原始版权归属: Copyright © 2025 Ke Xu (Luke)
// 本实现版权归属: Copyright © 2025 Sany
// 遵循 Apache License 2.0 授权
package register

import (
	"errors"
	"strconv"

	"gitee.com/xntk2381/cc/vm/module"
)

type MovCommand struct{}

func (MovCommand) Execute(parts []string, currentPC int, operandStack *module.OperandStack, localVariableStore *module.LocalVariableStore, callStack *module.CallStack) (int, error) {
	sourceIndex, err := strconv.Atoi(parts[1])
	if err != nil {
		return 0, errors.New("MOV: invalid source index")
	}
	destinationIndex, err := strconv.Atoi(parts[2])
	if err != nil {
		return 0, errors.New("MOV: invalid destination index")
	}

	// Retrieve the value from the local variable store at the source index
	frame, err := callStack.PeekFrame()
	if err != nil {
		return 0, err
	}
	value, err := frame.GetLocalVariableStore().GetVariable(sourceIndex)
	if err != nil {
		return 0, err
	}

	// Store the retrieved value into the destination index within the local variable store
	frame.GetLocalVariableStore().SetVariable(destinationIndex, value)

	// Return the updated program counter to continue to the next instruction
	return currentPC + 1, nil
}
